#!/usr/bin/env python3
"""
Build script for creating executable of Ollama Translator
"""

import os
import sys
import subprocess
import shutil
from pathlib import Path


def check_dependencies():
    """Check if required dependencies are installed"""
    required_packages = ['PyInstaller', 'requests', 'PyQt6']
    
    print("Checking dependencies...")
    for package in required_packages:
        try:
            __import__(package.lower().replace('-', '_'))
            print(f"✓ {package}")
        except ImportError:
            print(f"✗ {package} not found")
            return False
    return True


def create_build_directory():
    """Create build directory structure"""
    build_dir = Path("build")
    dist_dir = Path("dist")
    
    # Clean previous builds
    if build_dir.exists():
        shutil.rmtree(build_dir)
    if dist_dir.exists():
        shutil.rmtree(dist_dir)
    
    build_dir.mkdir(exist_ok=True)
    dist_dir.mkdir(exist_ok=True)
    
    return build_dir, dist_dir


def build_executable():
    """Build the executable using PyInstaller"""
    print("\nBuilding executable...")
    
    # Use the spec file
    spec_file = "ollama_translate.spec"
    
    if not Path(spec_file).exists():
        print(f"Error: {spec_file} not found")
        return False
    
    try:
        # Build using spec file
        result = subprocess.run([
            sys.executable, "-m", "PyInstaller",
            "--onefile",
            "--noconsole",
            "--name", "ollama_translate",
            "--specpath", "build",
            "main.py"
        ], check=True, capture_output=True, text=True)
        
        print("✓ Build completed successfully")
        return True
        
    except subprocess.CalledProcessError as e:
        print(f"Build failed: {e}")
        if e.stderr:
            print(f"Error output: {e.stderr}")
        return False


def package_with_spec():
    """Package using the spec file (more reliable)"""
    print("\nPackaging with spec file...")
    
    try:
        result = subprocess.run([
            sys.executable, "-m", "PyInstaller",
            "ollama_translate.spec",
            "--clean"
        ], check=True, capture_output=True, text=True)
        
        print("✓ Packaging completed successfully")
        return True
        
    except subprocess.CalledProcessError as e:
        print(f"Packaging failed: {e}")
        if e.stderr:
            print(f"Error output: {e.stderr}")
        return False


def verify_executable():
    """Verify the built executable"""
    executable_path = Path("dist") / "ollama_translate"
    
    if not executable_path.exists():
        print(f"Error: Executable not found at {executable_path}")
        return False
    
    # Check if it's executable
    if not os.access(executable_path, os.X_OK):
        print("Making executable...")
        os.chmod(executable_path, 0o755)
    
    # Check file size
    file_size = executable_path.stat().st_size
    print(f"✓ Executable created: {executable_path}")
    print(f"  Size: {file_size / (1024*1024):.2f} MB")
    
    return True


def create_installer_script():
    """Create an installation script for the executable"""
    script_content = """#!/bin/bash
# Installation script for Ollama Translator

echo "Installing Ollama Translator..."

# Check if Ollama is running
if ! pgrep -x "ollama" > /dev/null; then
    echo "Warning: Ollama service is not running"
    echo "Please start Ollama with: systemctl --user start ollama"
fi

# Copy executable to /usr/local/bin if user has permissions
if [ -w /usr/local/bin ]; then
    sudo cp dist/ollama_translate /usr/local/bin/
    echo "Installed to /usr/local/bin/ollama_translate"
else
    echo "Cannot install to /usr/local/bin (permission denied)"
    echo "You can run the executable directly from: dist/ollama_translate"
fi

echo "Installation complete!"
echo "Run with: ollama_translate"
"""
    
    with open("install.sh", "w") as f:
        f.write(script_content)
    
    os.chmod("install.sh", 0o755)
    print("✓ Created installation script: install.sh")


def main():
    """Main build function"""
    print("Ollama Translator - Build Script")
    print("=" * 50)
    
    # Check dependencies
    if not check_dependencies():
        print("\nPlease install missing dependencies:")
        print("pip install PyInstaller requests PyQt6")
        sys.exit(1)
    
    # Create build directories
    build_dir, dist_dir = create_build_directory()
    
    # Build executable
    if not package_with_spec():
        print("\nTrying alternative build method...")
        if not build_executable():
            print("\nBuild failed. Please check the errors above.")
            sys.exit(1)
    
    # Verify the executable
    if verify_executable():
        print("\n" + "=" * 50)
        print("BUILD SUCCESSFUL!")
        print("\nThe executable is located at: dist/ollama_translate")
        print("\nTo run the application:")
        print("  ./dist/ollama_translate")
        
        # Create installer script
        create_installer_script()
        
        print("\nTo install system-wide:")
        print("  ./install.sh")
    else:
        print("\nBuild verification failed.")
        sys.exit(1)


if __name__ == "__main__":
    main()